// 商品数据
const products = [
    {
        id: 1,
        name: "智能手机 X1",
        price: 1999,
        image: "images/product1.jpg",
        description: "高性能智能手机，6.5英寸屏幕",
        category: "electronics"
    },
    {
        id: 2,
        name: "无线蓝牙耳机",
        price: 299,
        image: "images/product2.jpg",
        description: "高音质无线蓝牙耳机",
        category: "electronics"
    },
    {
        id: 3,
        name: "男士休闲衬衫",
        price: 159,
        image: "images/product3.jpg",
        description: "纯棉男士休闲衬衫",
        category: "clothing"
    },
    {
        id: 4,
        name: "JavaScript高级程序设计",
        price: 99,
        image: "images/product4.jpg",
        description: "前端开发必备书籍",
        category: "books"
    },
    {
        id: 5,
        name: "智能电饭煲",
        price: 399,
        image: "images/product5.jpg",
        description: "多功能智能电饭煲",
        category: "home"
    },
    {
        id: 6,
        name: "进口牛奶",
        price: 69,
        image: "images/product6.jpg",
        description: "新西兰进口纯牛奶",
        category: "food"
    },
    {
        id: 7,
        name: "笔记本电脑",
        price: 5999,
        image: "images/product7.jpg",
        description: "高性能轻薄笔记本电脑",
        category: "electronics"
    },
    {
        id: 8,
        name: "女士连衣裙",
        price: 199,
        image: "images/product8.jpg",
        description: "夏季新款女士连衣裙",
        category: "clothing"
    }
];

// 加载商品列表
function loadProducts(category = null) {
    const productList = document.getElementById('productList');
    if (!productList) return;
    
    productList.innerHTML = '';
    
    let filteredProducts = products;
    if (category) {
        filteredProducts = products.filter(p => p.category === category);
    }
    
    filteredProducts.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <a href="product-detail.html?id=${product.id}">
                <div class="product-img">
                    <img src="${product.image}" alt="${product.name}">
                </div>
                <div class="product-info">
                    <h3 class="product-title">${product.name}</h3>
                    <div class="product-price">¥${product.price.toFixed(2)}</div>
                </div>
            </a>
            <button class="add-to-cart" data-id="${product.id}">加入购物车</button>
        `;
        productList.appendChild(productCard);
    });
    
    // 添加购物车事件
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', addToCart);
    });
}

// 添加到购物车
function addToCart(event) {
    const productId = parseInt(event.target.getAttribute('data-id'));
    const product = products.find(p => p.id === productId);
    
    if (!product) return;
    
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image,
            quantity: 1
        });
    }
    
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCartCount();
    
    // 显示添加成功提示
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = `${product.name} 已添加到购物车`;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.classList.add('show');
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 2000);
    }, 10);
}

// 搜索商品
function setupSearch() {
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    
    if (searchInput && searchBtn) {
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') performSearch();
        });
    }
}

function performSearch() {
    const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
    if (!searchTerm) return;
    
    const filteredProducts = products.filter(p => 
        p.name.toLowerCase().includes(searchTerm) || 
        p.description.toLowerCase().includes(searchTerm)
    );
    
    const productList = document.getElementById('productList');
    if (!productList) return;
    
    productList.innerHTML = '';
    
    if (filteredProducts.length === 0) {
        productList.innerHTML = '<p class="no-results">没有找到相关商品</p>';
        return;
    }
    
    filteredProducts.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <div class="product-img">
                <img src="${product.image}" alt="${product.name}">
            </div>
            <div class="product-info">
                <h3 class="product-title">${product.name}</h3>
                <div class="product-price">¥${product.price.toFixed(2)}</div>
                <button class="add-to-cart" data-id="${product.id}">加入购物车</button>
            </div>
        `;
        productList.appendChild(productCard);
    });
    
    // 添加购物车事件
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', addToCart);
    });
}

// 设置分类点击事件
function setupCategoryFilters() {
    const categoryItems = document.querySelectorAll('.category-item');
    if (categoryItems.length === 0) return;
    
    categoryItems.forEach(item => {
        item.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            loadProducts(category);
        });
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadProducts();
    setupSearch();
    setupCategoryFilters();
    
    // 添加通知样式
    const style = document.createElement('style');
    style.textContent = `
        .notification {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #4CAF50;
            color: white;
            padding: 15px 25px;
            border-radius: 5px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 1000;
        }
        .notification.show {
            opacity: 1;
        }
        .no-results {
            grid-column: 1 / -1;
            text-align: center;
            padding: 50px;
            color: #666;
        }
    `;
    document.head.appendChild(style);
});

